package org.bonorsoft.common.util;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.bonorsoft.common.core.exception.WexinReqException;
import org.bonorsoft.modules.api.wxbase.wxtoken.JwTokenAPI;


public class WxTokenAPI {

	private final static String appid = "wxf7b41fa89b384d55";
	private final static String appserct = "46e431494364f7939cf53e66c544b5b1";

	/**
	 * 获取微信公众号的access_token
	 * @return 
	 */
	public static  String getAccessToken() throws WexinReqException {
		String accessToken = JwTokenAPI.getAccessToken(appid, appserct);
		return accessToken;
	}

	public static Map<String, String> getConfig(HttpServletRequest request) throws WexinReqException {
		String accessToken = JwTokenAPI.getAccessToken(appid, appserct);
		String url = request.getParameter("url");
		String URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?" +
				"access_token="+ accessToken +"" +
				"&type=jsapi";
		System.out.println(url);

		JSONObject jsonObject = HttpUtil.httpRequest(URL, "GET", null);
		System.out.println(jsonObject);
		String ticket=jsonObject.getString("ticket");
		/*String jsapi_ticket = "jsapi_ticket";
		// 注意 URL 一定要动态获取，不能 hardcode
		String url = "http://example.com";*/
		Map<String, String> ret = WxUtil.sign(ticket, url);
		ret.put("appId",appid);
		return ret;
	}

	public static void redirectByAuthType(HttpServletRequest request, HttpServletResponse response) throws IOException {

		//如果网页授权作用域为snsapi_userinfo，则此时开发者可以通过access_token和openid拉取用户信息了。
		//snsapi_base
		try {
			String code = request.getParameter("code");
			//授权跳转到get方法：http://www.williamsunshine.club:8888/linksucai/openid?code=CODE&state=STATE
			if (code == null || code.length() == 0) {
				//第一步
				String weixinOauthURL = "https://open.weixin.qq.com/connect/oauth2/authorize?"
						+ "appid="+ appid +""
						+ "&redirect_uri=http://pay.cht.com.cn/linksucai/openid"
						+ "&response_type=code"
						+ "&scope=snsapi_userinfo"
						+ "&state=STATE#wechat_redirect";
				response.sendRedirect(weixinOauthURL);
			}else {
				//第二步
				//处理get方法：linksucai/openid?code=CODE&state=STATE获取openid和access_token
				String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
				requestUrl = requestUrl.replace("APPID", appid);
				requestUrl = requestUrl.replace("SECRET", appserct);
				requestUrl = requestUrl.replace("CODE", code);
				JSONObject json2 = HttpUtil.httpRequest(requestUrl, "POST", null);
				System.out.println(json2);
				String openid = (String) json2.get("openid");
				System.out.println("----------------get--openid-----------------" + openid);
				//一般处理到此即可，获取到openid

				//根据openid和access_token获取用户信息
				String refresh_token = (String) json2.get("REFRESH_TOKEN");
				String access_token = (String) json2.get("access_token");
				String token = "";
				String rid = "";
				if(oConvertUtils.isEmpty(access_token)){
					//第三步 刷新access_token（如果需要）
					//由于access_token拥有较短的有效期，当access_token超时后，可以使用refresh_token进行刷新，refresh_token有效期为30天，当refresh_token失效之后，需要用户重新授权。
					String refreshUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
					refreshUrl = refreshUrl.replace("APPID", appid);
					refreshUrl = refreshUrl.replace("REFRESH_TOKEN", refresh_token);
					JSONObject refreshinfo = HttpUtil.httpRequest(refreshUrl, "POST", null);
					System.out.println(refreshinfo);
					token = (String) refreshinfo.get("access_token");
					rid = (String) refreshinfo.get("openid");
				}else{
					token = access_token;
					rid = openid;
				}

				//第四步-access_token拥有较短的有效期，
				//String access_token = (String) json2.get("access_token");
				String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" +
						""+ token +"&openid="+ rid +"&lang=zh_CN";

				JSONObject uesrinfo = HttpUtil.httpRequest(userUrl, "GET", null);
				System.out.println(uesrinfo);
				//openid	用户的唯一标识
				//nickname	用户昵称
				//sex	用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
				//province	用户个人资料填写的省份
				//city	普通用户个人资料填写的城市
				//country	国家，如中国为CN
				//headimgurl	用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像），用户没有头像时该项为空。若用户更换头像，原有头像URL将失效。
				//privilege	用户特权信息，json 数组，如微信沃卡用户为（chinaunicom）
				//unionid	只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。 UnionID 来区分用户的唯一性

				String uid = (String) uesrinfo.get("openid");
				String nickname = (String) uesrinfo.get("nickname");
				String headimgurl = (String) uesrinfo.get("headimgurl");

				response.sendRedirect("https://www.williamsunshine.club?" + "openid=" + uid
						+"&nickname=" + nickname
						+"&headimgurl=" + headimgurl);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}



	}

}
